package com.six.controller;

import com.six.domain.dto.LoginDto;
import com.six.domain.dto.TokenVo;
import com.six.domain.entity.User;
import com.six.service.AuthService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import com.six.util.Result;

import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;
    private final RedisTemplate<String, String> redisTemplate;

    @PostMapping("/login")
    public Result<TokenVo> login(@Valid @RequestBody LoginDto dto) {

        return Result.ok(authService.login(dto));
    }
    @PostMapping("/logout")
    public Result<Void> logout(@AuthenticationPrincipal UserDetails user){
        String key = "user:token:" + user.getUsername();
        redisTemplate.delete(key);
        return Result.ok();
    }
    @PostMapping("/waiter")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> addWaiter(@RequestParam Long storeId,
                                  @RequestParam String name,
                                  @RequestParam String phone,
                                  @RequestParam String password) {
        authService.createWaiter(storeId, name, phone, password);
        return Result.ok();
    }

    @PatchMapping("/waiter/{id}")
    @PreAuthorize("hasRole('MANAGER')")
    public Result<Void> toggleWaiter(@PathVariable Long id, @RequestParam Boolean active) {
        authService.toggleWaiter(id, active);
        return Result.ok();
    }
    @PostMapping("/password")
    @PreAuthorize("isAuthenticated()")
    public Result<Void> updatePassword(@AuthenticationPrincipal UserDetails user,
                                       @RequestBody Map<String,String> req){
        String oldPwd = req.get("oldPassword");
        String newPwd = req.get("newPassword");
        authService.updatePassword(user.getUsername(), oldPwd, newPwd);
        return Result.ok();
    }

}
